import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  DatePicker,
  Table,
  Tag,
  InputNumber
} from 'antd';
import moment from 'moment';
import styles from './searchForm.less';

const { CheckableTag } = Tag;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const FormItem = Form.Item;
const { Option } = Select;
const Search = Input.Search;


@Form.create()
class Index extends PureComponent {
  state = {   
    expandForm: false,
    selectedRowKeys: [],
    ctagList: [],
    list:[
        {
            CustomerType: "会员",
            HeadImgUrl: "AvatarUrl",
            Id: 33,
            LastBuyTime: "2019-03-04 16:45:78",
            NickName: "NickName",
            Remark: null,
            SingleFee: 0,
            SystemTagType: "注册客户",
            Tags: null,
            Telephone: '12345678925',
            TotalFee: 0,
            TotalFeeNum: 0,
            TotalPoints: 0,
            WxRemark: null
        }
    ],
    formValues: {},
    paginationProps: {
      showSizeChanger: true,
      showQuickJumper: false,
      showTotal: total => `共 ${total} 条记录`,
      pageSize: 10,
      total: 1,
    },
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.SortName = `${sorter.field}`;
      params.Sort = `${sorter.order === 'ascend' ? 'Asc' : 'Desc'}`;
    } else {
      params.SortName = `Id`;
      params.Sort = `Desc`;
    }
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });    
  };

  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;      
      console.log(values);      
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 8 },
    };
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="关键词" {...formItemLayout}>
              {getFieldDecorator('KeyWord')(
                <Input placeholder="微信昵称/手机号/备注名" className="xkd-width-per-100" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="客户身份" {...formItemLayout}>
              {getFieldDecorator('MemberType')(
                <Select placeholder="请选择" className="xkd-width-per-100">
                  <Option value={0}>全部</Option>
                  <Option value={1}>客户</Option>
                  <Option value={2}>会员</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <Icon type="down" />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      cardList,
      allTagList,
    } = this.props;

    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 8 },
    };
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="关键词" {...formItemLayout}>
              {getFieldDecorator('KeyWord')(
                <Input placeholder="微信昵称/手机号/备注名" className="xkd-width-per-100" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="客户身份" {...formItemLayout}>
              {getFieldDecorator('MemberType')(
                <Select placeholder="请选择" className="xkd-width-per-100">
                  <Option value={0}>全部</Option>
                  <Option value={1}>客户</Option>
                  <Option value={2}>会员</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="会员卡" {...formItemLayout}>
              {getFieldDecorator('CardIds')(
                <Select placeholder="请选择" className="xkd-width-per-100" mode="multiple">
                  <Option value={1} >黄铜</Option>
                  <Option value={2} >黄铜</Option>
                  <Option value={3} >黄铜</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="最近消费时间" {...formItemLayout}>
              {getFieldDecorator('LastBuyDate')(
                <RangePicker className="xkd-width-per-100" placeholder={['开始日期', '结束日期']} />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="标签" {...formItemLayout}>
              {getFieldDecorator('TagIds')(
                <Select placeholder="请选择" className="xkd-width-per-100" mode="multiple">
                  <Option value={1} >黄铜</Option>
                  <Option value={2} >黄铜</Option>
                  <Option value={3} >黄铜</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="积分" {...formItemLayout}>
              {getFieldDecorator('Points')(
                <InputNumber className="xkd-width-per-100"/>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="成为客户时间" {...formItemLayout}>
              {getFieldDecorator('CreateDate')(
                <RangePicker className="xkd-width-per-100" placeholder={['开始日期', '结束日期']} />
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </div>
        </div>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  render() {
    const {
      loading,
    } = this.props;

    const { 
        paginationProps,
        list 
    } = this.state;
    
    const rowSelection = {      
      onChange: this.onSelectChange,
    };

    const columns = [
      {
        title: '客户名称',
        dataIndex: 'NickName',
        width: '15%',
      },
      {
        title: '手机号码',
        dataIndex: 'Telephone',
        width: '9%',
      },
      {
        title: '最近消费时间',
        dataIndex: 'LastBuyTime',
        width: '18%',
        render: val => <span className="xkd-text-ellipsis">{val}</span>,
        // mark to display a total number
        // needTotal: true,
      },
      {
        title: '积分',
        dataIndex: 'TotalPoints',
        width: '9%',
        align: 'right',
        sorter: true,
        render: val => (
          <span className="xkd-text-ellipsis" title={val}>
            {val}
          </span>
        ),
      },
      {
        title: '消费金额',
        dataIndex: 'TotalFee',
        width: '14%',
        align: 'right',
        sorter: true,
        render: val => (
          <span className="xkd-text-ellipsis" title={val}>
            ￥{val}
          </span>
        ),
      },
      {
        title: '消费次数',
        dataIndex: 'TotalFeeNum',
        width: '14%',
        align: 'right',
        sorter: true,
        render: val => (
          <span className="xkd-text-ellipsis" title={val}>
            {val}
          </span>
        ),
      },
      {
        title: '客单价',
        dataIndex: 'SingleFee',
        width: '12%',
        align: 'right',
        sorter: true,
        render: val => (
          <span className="xkd-text-ellipsis" title={val}>
            ￥{val}
          </span>
        ),
      },
      {
        title: '操作',
        width: '9%',
        align: 'right',
        render: (text, record) => (
          <Fragment>
            <a onClick={() => this.handleUpdateModalVisible(true, record)}>详情</a>
          </Fragment>
        ),
      },
    ];

    return (
      <Fragment>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button >操作一</Button>
              <Button >操作二</Button>
              <Button >操作三</Button>
            </div>
            <Table
              loading={loading}
              rowKey={record => record.Id}
              dataSource={list}
              columns={columns}
              rowSelection={rowSelection}
              onChange={this.handleStandardTableChange}
              pagination={paginationProps}
            />
          </div>
        </Card>        
      </Fragment>
    );
  }
}

export default connect(({ global, customerList, loading }) => ({
    global
  }))(Index);
